import type { App } from 'vue';
import { createI18n } from 'vue-i18n';
import elen from 'element-plus/dist/locale/en.mjs';
import loadEn from './lang/en';
import { setCache, getCache } from '@/utils/cache';

const CacheKey = 'locale';
const locale = ref(getCache(CacheKey) ?? 'en');
const message = ref();
const elLocale = computed(() => message.value?.elLocale ?? elen);

let i18n: ReturnType<typeof createI18n>;

export const useLocale = () => {
    return {
        elLocale,
        i18n,
        locale,
        message,
    };
};
export const LOCALE_OPTIONS = [
    { label: '中文', value: 'zh-cn' },
    { label: 'English', value: 'en' },
];
export const changeLocale = (value: string) => {
    locale.value = value;
};

export const setupI18n = async (app: App) => {
    const enMessage = await loadEn();

    const messages: Record<string, any> = {
        en: enMessage.message,
    };

    if (locale.value !== 'en') {
        const _locale = await import(`./lang/${locale.value}.ts`); // FIXME: 没有实现动态加载语言
        message.value = (await _locale.default?.()).message ?? {};
        messages[locale.value] = message.value;
    } else {
        message.value = enMessage.message;
    }

    i18n = createI18n({
        legacy: false,
        fallbackLocale: 'en',
        locale: locale.value,
        messages,
    });

    app.use(i18n);
};

watch(locale, async () => {
    setCache(CacheKey, locale.value);

    console.log('切换语言');
    const _locale = await import(`./lang/${locale.value}.ts`);
    message.value = (await _locale.default?.()).message ?? {};

    // i18n.global.locale = locale;
    i18n.global.setLocaleMessage(locale.value, message.value);
    (i18n.global.locale as any).value = locale.value;

    document.querySelector('html')?.setAttribute('lang', locale.value);
});
